function isInt(value) {
    return /^((?:0|[1-9]\d*))$/.test(value);
}

function isFloat(value) {
    return /^(\d+)+(\.\d{1,3})?$/.test(value);
}

var orderFactory = {
    keepDecFn: function (val, bit) {
        bit = Math.pow(10, bit);
        val *= bit;
        val = Math.round(val);
        val /= bit;
        return val;
    },
    queryString: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return r[2];
        return null;
    },
    cookie: function () {
        var cook = document.cookie.split(";");
        var userId;
        cook.map(function (c) {
            if (c.indexOf('userId') != -1) {
                userId = c.split("=")[1];
            }
        });
        if (userId) return userId;
    },
    extend: function (dist, source) {
        for (var i in source) if (source[i]) dist[i] = source[i];
    },
    addScroll: function () {
        $(window).scroll(function (e) {
        })
    },
    selectItemFn: function (name) {
        var self = this;
        return function (item, e) {
            var checked = e.target.checked;
            if (!self[name]) self[name] = {};
            if (checked)
                self[name][item.id] = item;
            else
                delete self[name][item.id];
            self.setState({selectItem: self[name]});
            self.state[name] = self[name];
            self.fresh();
        }
    },
    fresh: function () {
        this.setState({frest: !this.state.fresh});
    },
    minus: function (item) {
        if (item.goodsNum <= 1) return;
        item.goodsNum -= 1;
        this.fresh();
        this.calTotal();
    },
    calTotal: function () {
        var total = 0;
        this.state.list.forEach(function (item) {
            total += item.price * item.goodsNum;
        });
        this.state.total = this.keepDecFn(total, 3);
        this.fresh();
    },
    add: function (item) {
        item.goodsNum += 1;
        this.fresh();
        this.calTotal();
    },
    del: function (delItem) {
        var list = this.state.list;
        list.forEach(function (item, index) {
            if (delItem === item) list.splice(index, 1);
        });
        this.fresh();
        this.calTotal();
    },
    countFn: function (item, type, e) {
        var val = e.target.value;

        item.minLimit = item.minLimit ? item.minLimit : '';
        item.maxLimit = item.maxLimit ? item.maxLimit : '';
        this.fresh();

        //非数字校验
        if (val && isNaN(Number(val))) {
            return;
        }

        if (type == 'min') {
            item.minLimit = val;
        } else if (type == 'max') {
            item.maxLimit = val;
        }
        this.fresh();

        if (item.minLimit && Number(item.minLimit) <= 0) {
            item.errorsBegin = true;
        } else {
            item.errorsBegin = false;
        }
        if (item.maxLimit && Number(item.maxLimit) <= 0) {
            item.errorsEnd = true;
        } else {
            item.errorsEnd = false;
        }
        if ((item.minLimit && Number(item.minLimit) <= 0) || (item.maxLimit && Number(item.maxLimit) <= 0)) {
            item.errorMsg = '必须大于零';
            this.fresh();
            return;
        } else {
            item.errorMsg = '';
        }

        if (item.minLimit && item.maxLimit && Number(item.minLimit) >= Number(item.maxLimit)) {
            item.errorsBegin = true;
            item.errorsEnd = true;
            item.errorMsg = '采购数量起始不能大于或等于终止';
            this.fresh();
            return;
        } else {
            item.errorsBegin = false;
            item.errorsEnd = false;
            item.errorMsg = '';
        }

        var reg = /^(\d{1}|[1-9][0-9]*)$|^(0{1}|[1-9][0-9]*)\.\d{1,4}$/;
        if (item.minLimit && !reg.test(item.minLimit)) {
            item.errorsBegin = true;
        } else {
            item.errorsBegin = false;
        }
        if (item.maxLimit && !reg.test(item.maxLimit)) {
            item.errorsEnd = true;
        } else {
            item.errorsEnd = false;
        }
        if ((item.minLimit && !reg.test(item.minLimit)) || (item.maxLimit && !reg.test(item.maxLimit))) {
            item.errorMsg = '小数点后保留四位';
            this.fresh();
            return;
        }

        this.fresh();
    },
    coutnBlurFn: function (item, e) {    //数量输入框是去焦点时事件
        if (item.goodsNum == 0) item.goodsNum = 1;
        item.goodsNum = Number(item.goodsNum);
        this.fresh();
        this.calTotal();
    },
    customerNoteFn: function (e) {
        this.setState({customerNote: e.target.value});
    },
    checkNumber: function () {
        var flag = true;

        var orderGoods = this.state.list;
        orderGoods.forEach(function(item){
            if(!item.minLimit && !item.maxLimit){
                item.errorsBegin = true;
                item.errorsEnd = true;
                flag = false;
                return;
            }

            if(item.errorsBegin || item.errorsEnd){
                flag = false;
                return;
            }
        });
        this.fresh();

        return flag;
    },
    save: function (type) {
        if (!this.checkNumber()) {    //数量校验失败.停止执行
            return;
        }
        var msg = '确定提交订单？';
        if (type === 'DRAFT') {
            msg = '确定保存草稿？';
        }
        var data = {
            customerNote: this.state.customerNote,
            orderStatus: type,
            orderType: "SALE",
            purchaserId: this.cookie(),
            sellerId: this.state.purchaserId
        };
        var orderGoods = this.state.list.map(function (item) {
            return {
                amountDue: item.amountDue,
                goodsId: item.orderNo ? item.goodsId : item.id,
                minLimit: item.minLimit,
                maxLimit: item.maxLimit
            }
        });
        data.orderGoods = orderGoods;

        DialogComponent.init({
            'type': 'confirm', 'msg': msg, "success": function () {
                if (!this.state.orderNo) {
                    trdOrderService.save(data, function (res) {
                        if (res.errorCode == 0) {
                            this.setState({successBillNo: res.data, orderStatus: type});
                            PromptComponent.init({'type': 'success', 'msg': res.msg}).show();
                            $('html,body').animate({scrollTop: 0}, 300);
                        } else {
                            PromptComponent.init({'type': 'warning', 'msg': res.msg}).show();
                        }
                    }.bind(this));
                }
                else {
                    data.orderNo = this.state.orderNo;
                    trdOrderService.update(data, function (res) {
                        if (res.errorCode == 0) {
                            PromptComponent.init({'type': 'success', 'msg': res.msg}).show();
                            this.setState({successBillNo: this.state.orderNo, orderStatus: type});
                            $('html,body').animate({scrollTop: 0}, 300);
                        } else {
                            PromptComponent.init({'type': 'warning', 'msg': res.msg}).show();
                        }
                    }.bind(this));
                }
            }.bind(this)
        }).show();
    }
};
module.exports = orderFactory;